<?php
/**
 * @name /lib/public/Debug.php
 * @author Michael Foss <mfoss@clarionsafety.com>
 * @version 2007.07.02
 * 
 * Library for debugging functionality.
 */

ini_set('short_open_tag', 'On');

/**
 * Debug class.
 *
 */
class Debug {
  /**
   * Given an array of any dimensions,
   * returns an equivalent in a string format.
   *
   * @param Mixed[] $arr
   * @param integer $indent
   * @return string
   */
  function ArrayToString($arr, $indent = 0) {
    if (!is_array($arr))
      return $arr;
    $txt = '';
    foreach ($arr as $key => $val)
      if (is_array($val))
        $txt .= str_repeat("  ", $indent) . $key . ': array(' . count($val) . ")\n" .
                Debug::ArrayToString($val, $indent + 1);
      else
        $txt .= str_repeat("  ", $indent) . $key . ': ' . $val . "\n";
    return $txt;
  }

  /**
   * Outputs a string, array, or object to /[HOSTNAME]_tail.txt;
   * if $removeOldTailOnce is set to false,
   * does not remove the old tail file.
   *
   * @param Mixed $data
   * @param boolean $removeOldTailOnce
   */
  function Tail($txt, $removeOldTailOnce = true) {
    $myEnv =& GetSessionVars('Debug');
    if (is_array($txt))
      $txt = Debug::ArrayToString($txt);
    if (!$myEnv['Tail']) {
      $txt = "<" . date('Y.m.d') . ">\n1.\n" . $txt;
      $myEnv['Tail'] = 1;
    }
    else {
      $myEnv['Tail']++;
      $txt = $myEnv['Tail'] . ".\n" . $txt;
    }
    $txt .= "\n\n";
    $dir = $GLOBALS['INCROOT'];
    $filename = $GLOBALS['DOMAIN'] . '_tail.txt';
    $writeMethod = ($GLOBALS['OS'] == 'Windows' ? 'a+t' : 'a+b');
    if (!file_exists("$dir/$filename") || $removeOldTailOnce || $myEnv['Tail'] == 1) {
      $file = fopen("$dir/$filename", 'wt');
      fclose($file);
    }
    $file = fopen("$dir/$filename", $writeMethod);
    fputs($file, $txt);
    fclose($file);
  }

  /**
   * Sends debug info on a specific variable to the page.
   *
   * @param Mixed $var
   */
  function DebugVar($var) {
    $data = str_replace("\n", '<br />', str_replace(" ", "&nbsp;", htmlspecialchars(print_r($var, true))));
    $outerDivStyle = "width: 500px; position: absolute; top: 0px; left: 0px; border: 1px solid black; font: bold 8pt Arial; color: white; background-color: red; text-align: right;";
    $innerDivStyle = "text-align: left; margin: 5px; width: 490; height: 300px; border: 1px solid black; font: bold 10pt Courier New; background-color: #EEE; color: #111;";
    ?>
<div style="<?=$outerDivStyle ?>">
  <a href="javascript:;" onclick="parentNode.style.display = 'none'; return false;">close</a><br /><br />
  <div style="<?=$innerDivStyle ?>"><?=$data ?></div>
</div>
<?php
  }
}